<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div id="app">
        <!-- 监听组件事件 -->
        <!-- `add-student`是自定义事件，当触发就会调用父容器中的`addStudent`方法 -->
        <enter-input @add-student="addStudent"></enter-input>
        <my-list :students="students"></my-list>
    </div>
    <script src="../assets/vue2.js"></script>
    <script>
        Vue.component('enter-input', {
            data() {
                return {
                    student: ''
                }
            },
            methods: {
                addStudent() {
                    // 注意：事件名称定义时不要有大写字母出现
                    // add-student是自定义事件，this.student是传给addStudent的值
                    this.$emit('add-student', this.student);
                    this.student = ''; // 清空当前姓名
                }
            },
            template:
                `<input v-model="student" type="text" @keyup.enter="addStudent" />`
        })
        Vue.component('my-list', {
            props: {
                students: {
                    type: Array,
                    default: []
                },
            },
            template:
                `<ul>
                    <li v-for="name in students" :key="name">
                        {{ name }}
                    </li>
                </ul>`
        })
        const app = new Vue({
            el: '#app',
            data() {
                return {
                    students: ['张三', '李四', '王二']
                }
            },
            methods: {
                addStudent(student) {
                    this.students.push(student);
                }
            },
        });
    </script>
</body>

</html>